package com.brid.rocketmq.server.impl;

import com.brid.rocketmq.dao.ShareMapper;
import com.brid.rocketmq.domain.dto.ShareAuditDTO;
import com.brid.rocketmq.domain.dto.UserAddBonusMsgDTO;
import com.brid.rocketmq.domain.entity.Share;
import com.brid.rocketmq.domain.vo.ShareVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;
import java.util.Objects;
import java.util.Optional;

/**
 * @Author: 司军强
 * @Date: 17:23 2020/1/21
 * @Description:
 */
@Service
@Slf4j
public class RocketMqServiceImpl  {

    @Autowired
    private ShareMapper shareMapper;

    @Autowired
    private RocketMQTemplate rocketMqTemplate;

    /**
     * @param auditDTO
     * @return
     */
    public ShareVO auditById( ShareAuditDTO auditDTO) {
        //查询shar 是否存在 不存在抛异常
        Optional<Share> share1 = Optional.ofNullable(shareMapper.selectByPrimaryKey(auditDTO.getId()));
        if (!share1.isPresent()) {
            throw new IllegalArgumentException("参数非法，该分享不存在");
        }
        Share share = share1.get();
        switch (share.getAuditStatus()) {
            case "0":
                share.setAuditStatus("NOT_YET");
                break;
            case "1":
                share.setAuditStatus("PASS");
                break;
            case "2":
                share.setAuditStatus("REJECT");
            default:
                break;
        }
        if (!Objects.equals("NOT_YET", share.getAuditStatus())) {
            throw new IllegalArgumentException("参数非法 该分享已经审核通过");
        }
        //审核通过 设置状态为pass
        share.setAuditStatus(auditDTO.getAuditStatusEnum().toString());
        this.shareMapper.updateByPrimaryKey(share);
        // 入如果是 pass 则增加积分
        /**
         * 将消息发送给rocketmq中，让用户中心从rocketmq中消费
         * @param  destination 参数1  指定的topic名称
         * @param  payload 参数2  要发送的消息体
         */
        UserAddBonusMsgDTO build = UserAddBonusMsgDTO.builder()
                .bouns(1)
                .userId(share.getUserId())
                .build();
        try {
            rocketMqTemplate.convertAndSend("bonus", build);
        } catch (
                MessagingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
